package com.itheima.controller;

import com.itheima.anno.AuthAccess;
import com.itheima.common.ValidationEnum;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.mail.MessagingException;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Validated
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //    注册接口
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password, @RequestParam @Email String email, @RequestParam @Pattern(regexp = "^[0-9]{4}$") String code) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password) || !StringUtils.hasLength(email) || !StringUtils.hasLength(code)) {
            return Result.error("缺少必要的参数");
        }
        User user = userService.findByUsernameOrEmail(username, email);
        if (user == null) {
            userService.register(username, password, email, code);
            return Result.success();
        } else {
            return Result.error("用户名或邮箱已被占用");
        }
    }

    @AuthAccess
    @GetMapping("/checkUsername")
    public Result checkUsername(@RequestParam String username) {
        User user = userService.findByUsername(username);
        if (user != null) {
            return Result.error("用户名已被占用");
        } else {
            return Result.success();
        }
    }

    @AuthAccess
    @GetMapping("/checkEmail")
    public Result checkEmail(@RequestParam String email) {
        User user = userService.findByEmail(email);
        if (user != null) {
            return Result.error("邮箱已被占用");
        } else {
            return Result.success();
        }
    }

    @PostMapping("/addUser")
    public Result addUser(@RequestBody @Validated User user) {
        user.setPassword(Md5Util.getMD5String("123456"));
        String username = user.getUsername();
        User temp = userService.findByUsername(username);
        Map<String, Object> claims = ThreadLocalUtil.get();
        String loginUsername = (String) claims.get("username");
        User loginUser = userService.findByUsername(loginUsername);
        if (temp == null) {
            if (loginUser.getRole().equals("admin")) {

                userService.addUser(user);
                return Result.success();
            } else {
                return Result.error("你不是管理员");
            }
        } else {
            return Result.error("用户名已被占用");
        }
    }

    //    登陆接口
    @PostMapping("/loginAccount")
    public Result<String> loginAccount(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User loginUser = userService.findByUsername(username);
        if (loginUser == null) return Result.error("用户不存在");

        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            claims.put("role", loginUser.getRole());
            String token = JwtUtil.genToken(claims);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @AuthAccess
    @PostMapping("/loginEmail")
    public Result<String> loginEmail(@RequestParam @Email String email, @RequestParam @Pattern(regexp = "^[0-9]{4}$") String code) {
        if (!StringUtils.hasLength(email) || !StringUtils.hasLength(code)) {
            return Result.error("缺少必要的参数");
        }
        User emailUser = userService.loginEmail(email, code);
        if (emailUser == null) return Result.error("用户不存在");
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", emailUser.getId());
        claims.put("username", emailUser.getUsername());
        claims.put("role", emailUser.getRole());
        String token = JwtUtil.genToken(claims);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 1, TimeUnit.HOURS);
        return Result.success(token);
    }

    @AuthAccess
    @GetMapping("/email/{email}/{type}")
    public Result sendEmailCode(@PathVariable String email, @PathVariable Integer type) throws MessagingException {
        User user = userService.findByEmail(email);
        System.out.println("type" + type);

        if (type != ValidationEnum.REGISTER.getCode()) {
            if (user == null) {
                return Result.error("用户不存在");
            }
        }

        if (!StringUtils.hasLength(email)) {
            return Result.error("参数错误");
        }
        if (type == null) {
            return Result.error("参数错误");
        }
        userService.sendEmailCode(email, type);
        return Result.success();
    }

    @AuthAccess
    @PostMapping("/verifyByEmail")
    public Result<String> verifyByEmail(@RequestParam @Email String email, @RequestParam @Pattern(regexp = "^[0-9]{4}$") String verificationCode) {
        if (!StringUtils.hasLength(email) || !StringUtils.hasLength(verificationCode)) {
            return Result.error("缺少必要的参数");
        }
        User emailUser = userService.verifyByEmail(email, verificationCode);
        if (emailUser == null) return Result.error("用户不存在");
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("emailUserId", emailUser.getId());
        String token = JwtUtil.genToken(claims);
        return Result.success(token);
    }

    @AuthAccess
    //忘记密码实现
    @PatchMapping("/resetPwd")
    public Result resetPwd(@Pattern(regexp = "^\\S{5,16}$") String newPassword, @Pattern(regexp = "^\\S{5,16}$") String confirmPassword, String token) {
        if (!StringUtils.hasLength(newPassword) || !StringUtils.hasLength(confirmPassword)) {
            return Result.error("缺少必要的参数");
        }

        if (!newPassword.equals(confirmPassword)) {
            return Result.error("两次密码输入不一致");
        }
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer) map.get("emailUserId");
        userService.resetPwd(newPassword, id);
        return Result.success();
    }

    //    查询用户信息接口
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //这里我觉得应该用try catch包着，因为token可能会被篡改或者过期
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        String username = (String)claims.get("username");
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    @GetMapping("/userAllInfo")
    public Result<List<User>> userAllInfo() {
        List<User> allUserList = userService.getAllUserInfo();
        return Result.success(allUserList);
    }

    @GetMapping("/userManage")
    public Result<PageBean<User>> userManage(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String email
    ) {
        PageBean<User> pb = userService.userManage(pageNum, pageSize, username, nickname, email);
        return Result.success(pb);
    }

    //    更新用户信息（昵称，邮箱）
    @PutMapping("/update")
    public Result update(@RequestBody @Validated(User.Update.class) User user) {
        userService.update(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //更新用户密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        String oldPwd = params.get("oldPwd");
        String newPwd = params.get("newPwd");
        String rePwd = params.get("rePwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User loginUser = userService.findByUsername(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码不正确");
        }
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次密码输入不一致");
        }

        userService.updatePwd(newPwd);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();
    }

    @DeleteMapping
    public Result deleteUser(Integer id) {
        userService.deleteUser(id);
        return Result.success();
    }
}
